package com.xintonghua.bussiness.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.media.ExifInterface;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.ImageView;


import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.xintonghua.bussiness.MyAppLication;
import com.xintonghua.bussiness.R;
import com.xintonghua.bussiness.api.BaseApi;
import com.xintonghua.bussiness.api.myinterface.DataCallBack;
import com.xintonghua.bussiness.api.proxy.MyImageLoaderProxy;

import org.xutils.image.ImageOptions;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Target;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static org.xutils.common.util.IOUtil.copy;

public final class ImageTools {
    /**
     * 加载图片 方形图片
     *
     * @param url
     * @param image
     * @param defaultImage
     */
    public static void displayImage(String url, ImageView image, int defaultImage) {
        MyImageLoaderProxy.getInstance().displayImage(url, image, defaultImage);
    }

    public static void displayImage(String url, ImageView image) {
        MyImageLoaderProxy.getInstance().displayImage(url, image, R.mipmap.ic_image_loading);
    }

    public static void displayRoundedImage(String url, ImageView image) {
        MyImageLoaderProxy.getInstance().displayRoundedImage(url, image, R.mipmap.ic_image_loading);
    }

    public static void displayRoundedImage(String url, ImageView image, int defaultImage) {
        MyImageLoaderProxy.getInstance().displayRoundedImage(url, image, defaultImage);
    }

    /**
     * 加载圆形图片
     *
     * @param url
     * @param image
     * @param defaultImage
     */
    public static void displayCircleImage(String url, ImageView image, int defaultImage) {
        MyImageLoaderProxy.getInstance().displayCircleImage(url, image, defaultImage);
    }

    public static void displayCircleImage(String url, ImageView image) {
        MyImageLoaderProxy.getInstance().displayCircleImage(url, image, R.mipmap.ic_image_loading);
    }

    /**
     * 加载全路径图片地址
     *
     * @param url
     * @param image
     */
    public static void displayCompleteUrl(String url, ImageView image) {
        MyImageLoaderProxy.getInstance().displayCompleteUrl(url, image, R.mipmap.ic_image_loading);
    }

    public static void displayCircleCompleteUrl(String url, ImageView image, int defaultImage) {
        MyImageLoaderProxy.getInstance().displayCircleCompleteUrl(url, image, defaultImage);
    }

    public static void displayCircleCompleteUrl(String url, ImageView image) {
        MyImageLoaderProxy.getInstance().displayCircleCompleteUrl(url, image, R.mipmap.ic_image_loading);
    }

    public static void displayRoundedCompleteUrl(String url, ImageView image) {
        MyImageLoaderProxy.getInstance().displayRoundedCompleteUrl(url, image, R.mipmap.ic_image_loading);
    }

    /**
     * 加载file路径图片
     *
     * @param url
     * @param image
     */
    public static void displayFileImage(String url, ImageView image) {
        MyImageLoaderProxy.getInstance().displayFileImage(url, image, R.mipmap.ic_image_loading);
    }

    public static void displayRoundedFileImage(String url, ImageView image) {
        MyImageLoaderProxy.getInstance().displayRoundedFileImage(url, image, R.mipmap.ic_image_loading);
    }

    public static void displayCircleFileImage(String url, ImageView image, int defaultImage) {
        MyImageLoaderProxy.getInstance().displayCircleFileImage(url, image, defaultImage);
    }

    /**
     * 按比例裁剪图片
     *
     * @param uri         源图片地址
     * @param file        剪切输出地址
     * @param requestCode 请求码
     */
    public static void cropImageUri(Activity activity, Uri uri, File file, int requestCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        if (Build.MODEL.contains("HUAWEI")) {//华为特殊处理 不然会显示圆
            intent.putExtra("aspectX", 9998);
            intent.putExtra("aspectY", 9999);
        } else {
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
        }
        intent.putExtra("outputX", 1000);
        intent.putExtra("outputY", 1000);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        activity.startActivityForResult(intent, requestCode);
    }


    /**
     * 按比例裁剪图片
     *
     * @param uri         源图片地址
     * @param file        剪切输出地址
     * @param x           x轴的长度
     * @param y           y轴的长度
     * @param requestCode 请求码
     */
    public static void cropImageUriWithXY(Activity activity, Uri uri, File file, int x, int y, int requestCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", x);
        intent.putExtra("aspectY", y);
        intent.putExtra("outputX", 1000);
        intent.putExtra("outputY", 1000);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        activity.startActivityForResult(intent, requestCode);
    }


    /**
     * 根据路径得到bitmap
     *
     * @param imagePath
     * @return
     */
    public static Bitmap getBitmapByFile(String imagePath) {
        return BitmapFactory.decodeFile(new File(imagePath).getAbsolutePath());
    }

    /**
     * 根据图片的url路径获得Bitmap对象
     *
     * @param url
     * @return
     */
    public static Bitmap getBitmapByUrl(String url) {
        URL fileUrl = null;
        Bitmap bitmap = null;
        try {
            fileUrl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            HttpURLConnection conn = (HttpURLConnection) fileUrl
                    .openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 将drawable文件转化为bitmap文件
     *
     * @param
     * @param drawable
     * @return
     */
    public static Bitmap getBitMap(int drawable) {
        Resources res = MyAppLication.getContext().getResources();
        Bitmap bmp = BitmapFactory.decodeResource(res, drawable);
        return bmp;
    }

    /**
     * 通过网络URL获取bitmap
     *
     * @param url
     * @return
     */
    public static Bitmap GetLocalOrNetBitmap(String url) {
        Bitmap bitmap = null;
        InputStream in = null;
        BufferedOutputStream out = null;
        try {
            in = new BufferedInputStream(new URL(url).openStream(), 2 * 1024);
            final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
            out = new BufferedOutputStream(dataStream, 2 * 1024);
            copy(in, out);
            out.flush();
            byte[] data = dataStream.toByteArray();
            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            data = null;

            return bitmap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 得到缩放后的图片
     *
     * @param imagePath
     * @param scale
     * @return
     */
    public static Bitmap getBitmapFromFile(String imagePath, int scale) {
        BitmapFactory.Options opts = null;
        opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;//设置inJustDecodeBounds为true后，decodeFile并不分配空间，此时计算原始图片的长度和宽度
        BitmapFactory.decodeFile(imagePath, opts);
        opts.inSampleSize = scale;
        opts.inJustDecodeBounds = false;
        opts.inInputShareable = true;
        opts.inPurgeable = true;
        try {
            return BitmapFactory.decodeFile(imagePath, opts);
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 缩放图片
     *
     * @param imagePath 被缩放的原图路径
     * @param SCALE     缩放比例
     * @return
     */
    public static Bitmap zoomBitmap(String imagePath, int SCALE) {
        Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        // 图片的旋转度数
        int degree = readPictureDegree(imagePath);
        if (degree <= 0) {
            // 如果旋转度数小于等于0，就不旋转图片
            Matrix matrix = new Matrix();
            float scaleWidth = ((float) 1 / SCALE);
            float scaleHeight = ((float) 1 / SCALE);
            matrix.postScale(scaleWidth, scaleHeight);
            //创建新图片
            Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
            bitmap.recycle();
            return resizedBitmap;
        } else {
            // 如果旋转度数大于0，就旋转图片
            Matrix matrix = new Matrix();
            // 根据旋转度数旋转图片
            matrix.postRotate(degree);
            float scaleWidth = ((float) 1 / SCALE);
            float scaleHeight = ((float) 1 / SCALE);
            matrix.postScale(scaleWidth, scaleHeight);
            // 创建新图片
            Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
            bitmap.recycle();
            return resizedBitmap;
        }
    }

    /**
     * 读取照片信息中的旋转角度
     *
     * @param path 照片路径
     * @return角度
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 将图片保存到sd卡
     *
     * @param bitmap    要保存的图片
     * @param imagePath 要保存的地址
     */
    public static void savePhotoToSDCard(Bitmap bitmap, String imagePath) {
        if (checkSDCardAvailable()) {
            File imageFile = new File(imagePath);
            if (!imageFile.getParentFile().exists()) {
                imageFile.getParentFile().mkdirs();
            }
            FileOutputStream fileOutputStream = null;
            try {
                fileOutputStream = new FileOutputStream(imageFile);
                if (bitmap != null) {
                    if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream)) {
                        fileOutputStream.flush();
                    }
                }
            } catch (FileNotFoundException e) {
                imageFile.delete();
                e.printStackTrace();
            } catch (IOException e) {
                imageFile.delete();
                e.printStackTrace();
            } finally {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 检查sd卡是否可用
     *
     * @return
     */
    public static boolean checkSDCardAvailable() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * 获取控件宽高中的最小值（用于制作圆形头像）
     *
     * @param view
     * @return
     */
    public static int getImageCorner(ImageView view) {
        ViewGroup.LayoutParams para = view.getLayoutParams();
        return para.width > para.height ? para.height / 2 : para.width / 2;
    }

    /**
     * 图片圆形处理
     *
     * @param oldBitmap
     * @return
     */
    public static Bitmap getRoundedBitmap(Bitmap oldBitmap) {
        float radius = oldBitmap.getWidth() > oldBitmap.getHeight() ? oldBitmap.getHeight() : oldBitmap.getWidth();
        // 创建新的位图
        Bitmap roundedBitmap = Bitmap.createBitmap(oldBitmap.getWidth(), oldBitmap.getHeight(), Bitmap.Config.ARGB_8888);
        // 把创建的位图作为画板
        Canvas mCanvas = new Canvas(roundedBitmap);
        Paint mPaint = new Paint();
        // 给Paint加上抗锯齿标志
        mPaint.setAntiAlias(true);
        // 先绘制圆形
        mCanvas.drawCircle(oldBitmap.getWidth() / 2, oldBitmap.getHeight() / 2, radius / 2, mPaint);
        // 设置图像的叠加模式
        mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        // 绘制图像
        mCanvas.drawBitmap(oldBitmap, 0, 0, mPaint);
        return roundedBitmap;
    }

    /**
     * 正常不做任何处理的图片
     *
     * @param oldBitmap
     * @return
     */
    public static Bitmap getBitmap(Bitmap oldBitmap) {
        float radius = oldBitmap.getWidth() > oldBitmap.getHeight() ? oldBitmap.getHeight() : oldBitmap.getWidth();
        // 创建新的位图
        Bitmap roundedBitmap = Bitmap.createBitmap(oldBitmap.getWidth(), oldBitmap.getHeight(), Bitmap.Config.ARGB_8888);
        // 把创建的位图作为画板
        Canvas mCanvas = new Canvas(roundedBitmap);
        Paint mPaint = new Paint();
        // 给Paint加上抗锯齿标志
        mPaint.setAntiAlias(true);
        // 先绘制圆形
        mCanvas.drawCircle(oldBitmap.getWidth() / 2, oldBitmap.getHeight() / 2, radius / 1, mPaint);
        // 设置图像的叠加模式
        mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        // 绘制图像
        mCanvas.drawBitmap(oldBitmap, 0, 0, mPaint);
        return roundedBitmap;
    }


    /**
     * 将字符串转换成Bitmap类型
     *
     * @param string
     * @return
     */
    public static Bitmap stringToBitmap(String string) {
        Bitmap bitmap = null;
        try {
            byte[] bitmapArray;
            bitmapArray = Base64.decode(string, Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 将本地图片路径压缩成bitmap 并根据大小进行不同比例的压缩
     *
     * @param imagePath
     * @return
     */
    public static Bitmap compressImageToBitmap(String imagePath) {
        Bitmap bitmap = ImageTools.getBitmapByFile(imagePath);
        if (bitmap == null) {
            return null;
        }
        if (bitmap.getByteCount() < 100000) {
            bitmap = ImageTools.getBitmapFromFile(imagePath, 1);
        } else if (bitmap.getByteCount() < 1000000) {
            bitmap = ImageTools.getBitmapFromFile(imagePath, 3);
        } else if (bitmap.getByteCount() < 10000000) {
            bitmap = ImageTools.getBitmapFromFile(imagePath, 5);
        } else if (bitmap.getByteCount() < 100000000) {
            bitmap = ImageTools.getBitmapFromFile(imagePath, 10);
        } else {
            bitmap = ImageTools.getBitmapFromFile(imagePath, 15);
        }
        return bitmap;
    }

    /**
     * 将Bitmap转换成Base64字符串
     *
     * @param bitmap
     * @return
     */
    public static String bitmapToBase64String(Bitmap bitmap) {
        String string = null;
        ByteArrayOutputStream bStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, bStream);
        byte[] bytes = bStream.toByteArray();
        string = Base64.encodeToString(bytes, Base64.DEFAULT);
        return string;
    }

    /**
     * 通过图片路径得到base64
     *
     * @param imagePath
     * @return
     */
    public static String getBase64ByImagePath(String imagePath) {
        Bitmap bitmap = compressImageToBitmap(imagePath);
        if (bitmap == null) {
            return "";
        }
        String base64 = bitmapToBase64String(bitmap);
        //bitmap.recycle();
        return base64;
    }


    /**
     * 获取圆形图片
     *
     * @param imageRes
     * @return
     */
    public static ImageOptions getCircularOptions(int imageRes) {
        ImageOptions imageOptions = new ImageOptions.Builder()
                .setCircular(true)
                .setCrop(true)
                .setLoadingDrawableId(imageRes)
                .setFailureDrawableId(imageRes)
                .setImageScaleType(ImageView.ScaleType.CENTER_CROP)
                .build();
        return imageOptions;
    }

    /**
     * 获取方形图片
     *
     * @param imageRes
     * @return
     */
    public static ImageOptions getNotCircularOptions(int imageRes) {
        ImageOptions imageOptions = new ImageOptions.Builder()
                .setCircular(false)
                .setCrop(false)
                .setLoadingDrawableId(imageRes)
                .setFailureDrawableId(imageRes)
                .setImageScaleType(ImageView.ScaleType.FIT_XY)
                .build();

        return imageOptions;
    }

    /**
     * 获取带圆角的方形图片
     *
     * @param imageRes
     * @return
     */
    public static ImageOptions getRoundedOptions(int imageRes) {
        ImageOptions imageOptions = new ImageOptions.Builder()
                .setCircular(false)
                .setCrop(false)
                .setRadius(10)
                .setLoadingDrawableId(imageRes)
                .setFailureDrawableId(imageRes)
                .setImageScaleType(ImageView.ScaleType.FIT_XY)
                .build();

        return imageOptions;

    }

    public static Bitmap createVideoThumbnail(String url, int width, int height) {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        int kind = MediaStore.Video.Thumbnails.MINI_KIND;
        try {
            if (Build.VERSION.SDK_INT >= 14) {
                retriever.setDataSource(url, new HashMap<String, String>());
            } else {
                retriever.setDataSource(url);
            }
            bitmap = retriever.getFrameAtTime();
        } catch (IllegalArgumentException ex) {
            // Assume this is a corrupt video file
        } catch (RuntimeException ex) {
            // Assume this is a corrupt video file.
        } finally {
            try {
                retriever.release();
            } catch (RuntimeException ex) {
                // Ignore failures while cleaning up.
            }
        }
        if (kind == MediaStore.Images.Thumbnails.MICRO_KIND && bitmap != null) {
            bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
                    ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        }
        return bitmap;
    }
    /**
     * 多图上传
     */
    public static void loadImages(final Activity activity, final List<String> imageList, final DataCallBack callBack, final int order) {
        final List<String> images = new ArrayList<>();
        for (int i = 0; i < imageList.size(); i++) {
            DialogUtils.showWithStatus("正在上传图片", activity);
            final String key = String.valueOf(System.currentTimeMillis()) + ((int) Math.random() * 1000000) + ".png";
            final String objectKey = "image/" + key;
            Log.e("x_log", "key:" + key);
            // 构造上传请求
            PutObjectRequest put = new PutObjectRequest("pandaouba", objectKey, imageList.get(i));
            // 异步上传时可以设置进度回调
            put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
                @Override
                public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                }
            });
            MyAppLication.getOss().asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                @Override
                public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                    images.add(key);
                    Log.e("x_log", "key:" + key);
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (imageList.size() == images.size()) {
                                DialogUtils.disMissDialog();
                                callBack.dataBack(images, order);
                            }
                        }
                    });
                }

                @Override
                public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            DialogUtils.disMissDialog();
                            MyUtils.mToast(activity, "上传失败");
                        }
                    });
                    if (clientExcepion != null) {// 请求异常
                        clientExcepion.printStackTrace(); // 本地异常如网络异常等
                    }
                    if (serviceException != null) {// 服务异常
                        Log.e("ErrorCode", serviceException.getErrorCode());
                        Log.e("RequestId", serviceException.getRequestId());
                        Log.e("HostId", serviceException.getHostId());
                        Log.e("RawMessage", serviceException.getRawMessage());
                    }
                }
            });
        }

    }

    /**
     * 单图上传
     */
    public static void loadImage(final Activity activity, String imagePath, final DataCallBack callBack, final int order) {
        DialogUtils.showWithStatus("正在上传图片", activity);
        final String key = String.valueOf(System.currentTimeMillis()) + ((int) Math.random() * 1000000) + ".png";
        final String objectKey = "image/" + key;
        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest("pandaouba", objectKey, imagePath);
        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
            }
        });
        MyAppLication.getOss().asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        callBack.dataBack(key, order);
                        DialogUtils.disMissDialog();
                    }
                });
            }
            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        DialogUtils.disMissDialog();
                    }
                });
                if (clientExcepion != null) {// 请求异常
                    clientExcepion.printStackTrace(); // 本地异常如网络异常等
                }
                if (serviceException != null) {// 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
            }
        });
    }

}